from apps.goods.models import GoodsChannel
from  apps.users.models import User
from django.contrib.auth.backends import ModelBackend
import re
def get_user_by_account(account):
    try:
        if re.match('^1[3-9]\d{9}$', account):
            user=User.objects.get(mobile=account)
        else:
            user=User.objects.get(username=account)
    except:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if  request is None:
            try:
                user=User.objects.get(username=username,is_staff=True)
                return user
            except:
                return None

        else:
            user=get_user_by_account(username)
            if user and user.check_password(password):
                return user
            return None


def get_categories():
    categories = {}
    channels = GoodsChannel.objects.all()

    for channel in channels:
        group_id = channel.group_id

        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })

        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)


    return categories